package com.juku2024.juku.tools

import android.content.ComponentCallbacks
import android.content.Context
import android.content.res.Configuration
import android.content.res.Resources

object AdapterScreenUtils {

    private var finalScaledDensity: Float = 0.toFloat()
    private var finalDensity: Float = 0.toFloat()
    private var finalDensityDpi: Int = 0

    @Suppress("DEPRECATION")
    fun adaptScreen(context: Context, resources: Resources?, sizeInPx: Int): Resources? {
        if (resources == null || sizeInPx <= 0)
            return resources
        try {
            val systemDm = resources.displayMetrics
            if (finalScaledDensity == 0f && finalDensity == 0f && finalDensityDpi == 0) {
                val isVerticalSlide = isScreenVertical(resources)
                finalDensity = if (isVerticalSlide) {
                    systemDm.widthPixels / sizeInPx.toFloat()
                } else {
                    systemDm.heightPixels / sizeInPx.toFloat()
                }
                finalScaledDensity = finalDensity * (systemDm.scaledDensity / systemDm.density)
                finalDensityDpi = (160 * finalDensity).toInt()

                context.applicationContext.unregisterComponentCallbacks(object : ComponentCallbacks {
                    override fun onConfigurationChanged(newConfig: Configuration) {
                        systemDm.scaledDensity = context.applicationContext.resources.displayMetrics.scaledDensity
                    }

                    @Deprecated("Deprecated in Java")
                    override fun onLowMemory() {

                    }


                })

                systemDm.density = finalDensity
                systemDm.scaledDensity = finalScaledDensity
                systemDm.densityDpi = finalDensityDpi
            } else {
                systemDm.density = finalDensity
                systemDm.scaledDensity = finalScaledDensity
                systemDm.densityDpi = finalDensityDpi
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return resources
    }

    /**
     * 获取当前activity的屏幕方向  默认竖直方向
     *
     * @param resources
     * @return
     */
    private fun isScreenVertical(resources: Resources?): Boolean {
        // 默认竖直方向
        var isScreenVertical = true
        if (resources != null) {
            val configuration = resources.configuration
            if (configuration != null) {
                isScreenVertical = configuration.orientation == Configuration.ORIENTATION_PORTRAIT
            }
        }
        return isScreenVertical
    }
}